package com.jewelry.controller;

import com.jewelry.entity.Address;
import com.jewelry.entity.User;
import com.jewelry.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    //添加地址信息
    @PostMapping("addAddress")
    public Map<String,Object> addAddress(@RequestBody Address address, HttpSession session){
        Map<String,Object> map = new HashMap<>();
        User user = (User) session.getAttribute("user");
        address.setUserId(user.getUserId());
        addressService.save(address);
        map.put("message","success");
        return map;
    }

    //删除地址信息
    @DeleteMapping("deleteAddress/{addressId}")
    public Map<String,Object> deleteAddress(@PathVariable Integer addressId) {
        Map<String,Object> map = new HashMap<>();
        addressService.removeById(addressId);
        map.put("message","success");
        return map;
    }

    //更改地址信息
    @PutMapping("updateAddress")
    public Map<String,Object> updateAddress(@RequestBody Address address) {
        Map<String,Object> map = new HashMap<>();
        addressService.updateById(address);
        map.put("message","success");
        return map;
    }

    //根据addressId查询一个地址
    @GetMapping("showAddressById/{addressId}")
    public Address showAddressById(@PathVariable Integer addressId){
        Address address = addressService.getById(addressId);
        return address;
    }

    //查询一个user下的所有地址
    @GetMapping("findAllAddress")
    public Map<String,Object> findAllAddress(HttpSession session) {
        Map<String,Object> map = new HashMap<>();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        if (user == null){
            map.put("message","not-login");
        }
        List<Address> addressList = addressService.selectAddressByUserId(userId);
        map.put("allAddress",addressList);
        return map;
    }

}
